<template>
  <div style="padding: 10px;">
    <el-row >
      <el-col>
        <div style="display: flex;">
          <div>
            <el-form :model="list_params" ref="searchForm"  size="small" :inline="true" @submit.native.prevent="() => handleQuery()">
              <el-form-item label="" prop="ruleType">
                <el-select filterable  v-model="list_params.ruleType" placeholder="请选择规则类型" >
                  <el-option  v-for="item in dict.type.rule_type" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="" prop="productNames">
                <el-select filterable  v-model="list_params.goodsName" placeholder="请选择产品" clearable  :style="{width: '100%'}">
                  <el-option v-for="item in all_product_list" :key="item.id" :label="item.name" :value="item.name"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary"  size="mini" native-type="submit">搜索</el-button>
                <el-button  size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div style="flex: 1;"></div>
          <div>
            <!--            <el-button>删除</el-button>-->
            <!-- <el-button @click="handleExport">导出</el-button>
            <el-button>导入</el-button> -->
            <el-button type="primary" @click="addCustom" >添加</el-button>
          </div>
        </div>
      </el-col>
      <el-col>
        <div style="margin-top: 10px;">
          <el-table :data="table_data" @selection-change="handleSelectionChange"  :height="table_height">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="类型" prop="ruleType">
              <template slot-scope="scope" >
                <dict-tag :options="dict.type.rule_type" :value="scope.row.ruleType"/>
              </template>
            </el-table-column>
            <el-table-column label="产品" prop="goodsName"></el-table-column>
            <el-table-column label="天数" prop="ruleDays"></el-table-column>
            <el-table-column label="接收人" prop="receiverNames"></el-table-column>
            <el-table-column label="状态" prop="ruleStatus">
              <template slot-scope="scope" >
                {{scope.row.ruleStatus==1?'启用':'禁用'}}
              </template>
            </el-table-column>
            <el-table-column label="备注" prop="remark"></el-table-column>
            <el-table-column label="创建时间" prop="createTime"></el-table-column>
            <el-table-column label="操作" width="120" >
              <template slot-scope="scope" >
<!--                <el-button-->
<!--                  size="mini"-->
<!--                  type="text"-->
<!--                  @click="showInfo(scope.row)"-->
<!--                >查看</el-button>-->
                <el-button
                  size="mini"
                  type="text"
                  @click="editInfo(scope.row)"
                >编辑</el-button>
                <el-popconfirm
                  title="确定删除吗？"
                  @confirm="c_delete(scope.row)"
                >
                  <el-button style="margin-left: 10px;"
                             slot="reference"
                             size="mini"
                             type="text"
                  >删除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="list_total>0"
            :total="list_total"
            :page.sync="list_params.pageNum"
            :limit.sync="list_params.pageSize"
            @pagination="getList"
          />
        </div>
      </el-col>
    </el-row>
    <el-dialog  :visible.sync="add_custom_dialog_show" title="添加客户" width="680px" style="border-radius: 10px;" @close="close">
      <el-form  ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
        <el-row>

          <el-col :span="24">
            <el-form-item label="规则类型" prop="ruleType">
              <el-select filterable  v-model="formData.ruleType"  >
                <el-option  v-for="item in dict.type.rule_type" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="goodsName" label="产品">
              <el-select filterable  v-model="formData.goodsName" placeholder="请选择产品" multiple collapse-tags clearable  >
                <el-option v-for="item in all_product_list" :key="item.id" :label="item.name" :value="item.name"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" >
            <el-form-item label="接收人" prop="receiverIds">
              <el-select filterable  v-model="formData.receiverIds" multiple collapse-tags >
                <el-option v-for="user in user_list" :value="user.userId" :label="user.nickName" ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="天数" prop="ruleDays">
              <el-input-number v-model="formData.ruleDays" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="是否启用" prop="title">
              <el-switch v-model="formData.ruleStatus" :active-value="1" :inactive-value="0"  ></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" placeholder="请输入备注"  show-word-limit clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="title" style="background: #F3F4F6;margin: -20px;padding: 20px;height: 58px;border-radius: 10px;">{{formData.id?'编辑预警规则':'新增预警规则'}}</div>
      <div slot="footer" >
        <el-button @click="close" >取消</el-button>
        <el-button type="primary" @click="handleConfirm">保存</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { list,add,update,detail,del} from "@/api/alert/rule";
import { listUser } from "@/api/system/user";
import { getToken } from "@/utils/auth";
import { mapGetters } from 'vuex'
import store from '@/store'
import { AllList } from '@/api/product/info'
export default {
  name: 'custom',
  dicts:['rule_type'],
  ...mapGetters([
    'user_id'
  ]),
  data() {
    return {
      table_height:window.innerHeight - 300,
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      add_custom_dialog_show:false,
      edit_custom_dialog_show:false,
      table_data:[],
      tmp_data:[],
      formData:{
        ruleDays:1,
      },
      formDataInit:{
        ruleDays:1,
      },
      formEditData:{
        phoneNumber:'',
        customerName:'',
        customerNum:'',
        customerClassify:'',
        enable:1,
        data_enable:true,
        depositBank:'',
        accountName:'',
        account:'',
        pictures:'',
        createBy:''
      },
      pictures:[],
      rules:{
        ruleDays:[{
          required: true,
          message: '请输入规则天数',
          trigger: 'blur'
        }],
        ruleType:[{
          required: true,
          message: '请选择规则类型',
          trigger: 'change'
        }],
        receiverId:[{
          required: true,
          message: '请选择接收人',
          trigger: 'change'
        }],
        receiverIds:[{
          required: true,
          message: '请选择接收人',
          trigger: 'change'
        }],
        goodsName:[{
          required: true,
          message: '请选择产品',
          trigger: 'change'
        }],
      },
      ids:[],
      list_params:{
        pageNum:1,
        pageSize:10,
        title:'',
        sendType:'',
        sendTime:[]
      },
      list_total:0,
      user_list:[],
      info_dialog_show:false,
      info:{},
      all_product_list:[]
    }
  },
  created() {
    this.getList()
    this.getUserList();
    this.getAllProductList()
  },
  methods:{
    getUserList(){
      listUser({is_page:0}).then((res)=>{
        this.user_list = res.rows
        console.log(res.rows)
      })
    },
    getAllProductList(){
      AllList().then(res => {
        this.all_product_list = res.rows;
      })
    },
    getList(){
      let params = {...this.list_params}

      // if (this.list_params.sendTime.length > 0){
      //   params.startTime = this.list_params.sendTime[0]+' 00:00:00'
      //   params.endTime = this.list_params.sendTime[1] + ' 23:59:59'
      // }
      list(params).then(res => {
        this.table_data = res.rows;
        this.list_total = res.total;
      })
    },
    addCustom(){
      this.formData = {}
      this.formData = {
        ...this.formDataInit
      }
      this.add_custom_dialog_show = true;
      this.$refs['elForm'].resetFields();

    },
    close(){
      this.$refs['elForm'].resetFields();
      this.add_custom_dialog_show = false
      this.formData = this.formDataInit
    },
    handleConfirm(){
      this.$refs['elForm'].validate((valid)=>{
        if (valid){
          let formData = this.formData;
          formData.receiverIds = formData.receiverIds.join(',')
          formData.goodsName = formData.goodsName.join(',')
          if (this.formData.id){
            update(formData).then((res)=>{
              this.add_custom_dialog_show = false
              this.getList()
              this.$refs['elForm'].resetFields();

            })
          }else {
            add(formData).then((res)=>{
              this.add_custom_dialog_show = false
              this.getList()
              this.$refs['elForm'].resetFields();

            })
          }
        }
      });
    },
    handleUpdate(){
      this.$refs['elEditForm'].validate((valid)=>{
        if (valid){
          let formData = this.formEditData;
          formData.createBy = store.getters.user_id;
          formData.enable = formData.enable?0:1

          this.edit_custom_dialog_show = false
          console.log(formData)
          update(formData).then(res=>{
            this.getList()
          })
          this.$refs['elEditForm'].resetFields();
        }
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    handleExport() {
      this.download('xnf/customer/export', {
        ...this.queryParams
      }, `customer${new Date().getTime()}.xlsx`)
    },
    handleEnable(enable){
      console.log(this.ids);
      if (this.ids.length == 0){
        this.$message({
          message: '请选择要操作的数据',
          type: 'warning'
        });
        return
      }
      handleEnable(this.ids,enable).then(res => {
        this.getList()
      })
    },
    editInfo(row){
      let id = row.id;
      detail(id).then(res => {
        let receiverIds = res.data.receiverIds.split(',').map(item => {
          return parseInt(item)
        })
        let goodsName = res.data.goodsName.split(',');
        this.formData = {
          ...this.formData,
          ...res.data,
          receiverIds:receiverIds,
          goodsName:goodsName,
          ruleType:res.data.ruleType+''
        }
        this.add_custom_dialog_show = true
      })
    },
    field101BeforeUpload(){},
    c_delete(row){
      let id = row.id;
      del(id).then(res => {
        this.$message.success('删除成功')
        this.getList()
      })
    },
    handleQuery(){
      this.list_params.pageNum = 1;
      this.getList();
    },
    resetQuery(){
      this.$refs['searchForm'].resetFields();
      this.list_params = {
        pageNum: 1,
        pageSize: 10,
      }
      this.getList();
    },
    onSendTypeChange(){
      this.formData = {
        ...this.formData,
        userIds:[],
        roleIds:[]
      }
    },
    showInfo(row){
      this.info = row;
      this.info_dialog_show = true
    }
  }
}
</script>

<style scoped>
.information-main-content img{
  max-width: 100%;
  height: auto;
}
</style>
<style >
.information-main-content img{
  max-width: 100%;
  height: auto;
}
</style>
